package com.example.secondhandmall.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.secondhandmall.R;
import com.example.secondhandmall.activity.DetailActivity;
import com.example.secondhandmall.activity.LoginActivity;
import com.example.secondhandmall.adapter.GoodsAdapter;
import com.example.secondhandmall.api.Api;
import com.example.secondhandmall.api.ApiConfig;
import com.example.secondhandmall.api.MyCallback;
import com.example.secondhandmall.entity.GoodsEntity;
import com.example.secondhandmall.entity.GoodsListResponse;
import com.example.secondhandmall.entity.GoodsSimpleEntity;
import com.example.secondhandmall.entity.PhotoEntity;
import com.example.secondhandmall.util.StringUtils;
import com.google.gson.Gson;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.SpinnerStyle;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Random;

public class GoodsFragment extends BaseFragment {

    private String title;
    private String category;
    private String imgurl1;
    private String imgurl2;
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private int pageNum = 1;
    private GoodsAdapter goodsAdapter;
    private List<GoodsSimpleEntity> datas;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
//            goodsAdapter.setDatas(datas);
//            goodsAdapter.notifyDataSetChanged();
            switch (msg.what) {
                case 0:
                    goodsAdapter.setDatas(datas);
                    goodsAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    public GoodsFragment() {
    }

    public static GoodsFragment newInstance(String title) {
        GoodsFragment fragment = new GoodsFragment();
        fragment.title = title;
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_goods;
    }

    @Override
    protected void initView() {
        recyclerView = mRootView.findViewById(R.id.recyclerView);
        refreshLayout = mRootView.findViewById(R.id.refreshLayout);
    }

    @Override
    protected void initData() {
        switch (title) {
            case "全部":
                category = "1";
                imgurl1 = "https://img.alicdn.com/bao/uploaded/i2/2205308485750/O1CN01q9ySzz1sLY4UnDOWB_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded/i4/1883877801/O1CN01jV2io727UuBR0DjuD_!!1883877801.jpg_200x200q90.jpg_.webp";
                break;
            case "鞋服":
                category = "2";
                imgurl1 = "https://img.alicdn.com/bao/uploaded/i1/880004424/O1CN01hphVL41iYErpaI0Gz_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded/i1/1729128393/O1CN01X54gIz2Bs2rNqc5tf_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                break;
            case "数码":
                category = "3";
                imgurl1 = "https://img.alicdn.com/bao/uploaded///gma.alicdn.com/bao/uploaded/i3/44368848/O1CN01LwNmVQ2FER47yUOUd_!!0-saturn_solar.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded/i2/373559220/O1CN01EGoCAx2HyoKWG8qK6_!!373559220.jpg_200x200q90.jpg_.webp";
                break;
            case "洗护":
                category = "4";
                imgurl1 = "https://img.alicdn.com/bao/uploaded/i2/2201203762970/O1CN01ahL6Qk1XoIz4Gk260_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded/i3/2380039536/O1CN013nXd0I2KJXXVdMs08_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                break;
            case "食品":
                category = "5";
                imgurl1 = "https://img.alicdn.com/bao/uploaded/i2/2206666316507/O1CN01lHVw9W1xwFsBgXJjq_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded/i2/1878258665/O1CN01pK26a42Dscbyj3g5T_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                break;
            case "手机":
                category = "6";
                imgurl1 = "https://img.alicdn.com/bao/uploaded///gma.alicdn.com/bao/uploaded/i3/110371600/O1CN016o6HbU1NgqNWRsgiw_!!0-saturn_solar.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded///gma.alicdn.com/bao/uploaded/i4/117615206/O1CN01GSlo461oKOc7ZIopx_!!0-saturn_solar.jpg_200x200q90.jpg_.webp";
                break;
            case "家具":
                category = "7";
                imgurl1 = "https://img.alicdn.com/bao/uploaded/i2/3175367109/O1CN01A0CSz222NyIPWv4Bi_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded///gma.alicdn.com/bao/uploaded/i1/1520260198/O1CN01tamiak1DKj7d3a2Kn_!!0-saturn_solar.jpg_200x200q90.jpg_.webp";
                break;
            case "玩具":
                category = "8";
                imgurl1 = "https://img.alicdn.com/bao/uploaded/i1/2493965190/O1CN01j4ARKR1oD4GRsrc3r_!!0-item_pic.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded/i4/3937219703/O1CN01SDh3xv2LY1jeFgRYe_!!3937219703-0-C2M.jpg_200x200q90.jpg_.webp";
            case "其他":
                category = "8";
                imgurl1 = "https://img.alicdn.com/bao/uploaded///gma.alicdn.com/bao/uploaded/i3/1238220127/O1CN010tTk861CoD0Xo4e5C_!!0-saturn_solar.jpg_200x200q90.jpg_.webp";
                imgurl2 = "https://img.alicdn.com/bao/uploaded///gma.alicdn.com/bao/uploaded/i2/113235841/O1CN01VvWdIE1t1E2pJT0Rv_!!0-saturn_solar.jpg_200x200q90.jpg_.webp";
                break;
        }
//        showToast("2222");

        //刷新加载
//        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
//        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        //设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));
        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                pageNum = 1;
//                localGoodsList(true, pageNum);
                getGoodsList();
            }
        });
//        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(RefreshLayout refreshlayout) {
////                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
//                pageNum++;
//                localGoodsList(false, pageNum);
////                getGoodsList(false);
//            }
//        });

        //网格布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        goodsAdapter = new GoodsAdapter(getActivity());
        recyclerView.setAdapter(goodsAdapter);
        goodsAdapter.setOnItemClickListener(new GoodsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int id) {
                //                showToast("点击");
//                HashMap<String,Object> detail =new HashMap<>();
//                detail.put("id",id);
//                detail.put("name",name);
                navigateTo(DetailActivity.class, "detail", id);
            }
        });

//        test();
//        showToast("11111");
//        localGoodsList(true, pageNum);
        getGoodsList();
    }

    private void test() {
        showToast("有问题！");
    }

    private void getGoodsList() {
        String account = getStringFromSp("account");
        if (!StringUtils.isEmpty(account)) {
            HashMap<String, Object> params = new HashMap<>();
//            params.put("account", account);
//            params.put("page", pageNum);
//            params.put("limit", ApiConfig.PAGE_SIZE);
//            params.put("category", category);
            if(title!="全部")params.put("type",title);
            Api.config(ApiConfig.GOODS_LIST_BY_CATEGORY, params).getRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    System.out.println(res);
                    refreshLayout.finishRefresh();
                    GoodsListResponse goodsListResponse = new Gson().fromJson(res, GoodsListResponse.class);
                    if (goodsListResponse != null && goodsListResponse.getCode() == 200) {
                        datas = goodsListResponse.getData();
                        for (int i = datas.size() -1; i >= 0; i--) {
                            if (datas.get(i).getDel() != 0)
                            datas.remove(i);
                        }
                        if (datas != null && datas.size() > 0) {
                            mHandler.sendEmptyMessage(0);
//                            goodsAdapter.setDatas(datas);
//                            goodsAdapter.notifyDataSetChanged();
                        } else {
                                showToastSync("暂时无法加载数据！");
                        }
                    }
                }

                @Override
                public void onFailure(Exception e) {
                        refreshLayout.finishRefresh(true);
                        showToastSync("刷新失败！");
                }
            });
        } else {
            navigateTo(LoginActivity.class);
            showToast("请先登录");
        }
    }

    private void localGoodsList(boolean isRefresh) {
        //本地模拟数据
//        List<GoodsEntity> datas = new ArrayList<>();
        List<GoodsSimpleEntity> list = new ArrayList<>();

        if (pageNum == 1) {
            for (int i = 0; i < 8; i++) {
                GoodsSimpleEntity goodsSimpleEntity = new GoodsSimpleEntity();
                goodsSimpleEntity.setGoodsName("nike 纯白色棉服");
                goodsSimpleEntity.setGoodsPrice(30.00);
                goodsSimpleEntity.setUserName("布克");
                List<PhotoEntity> photoEntities = new ArrayList<>();
                PhotoEntity photoEntity1 = new PhotoEntity();
                photoEntity1.setGoodsPhotoUrl(imgurl1);
                PhotoEntity photoEntity2 = new PhotoEntity();
                photoEntity2.setGoodsPhotoUrl(imgurl2);
                photoEntities.add(photoEntity1);
                photoEntities.add(photoEntity2);
                goodsSimpleEntity.setUrl(photoEntity1);
                goodsSimpleEntity.setUserPhoto(imgurl1);
                goodsSimpleEntity.setGoodsId(22);
//                goodsEntity.setDetail("nike 纯白色棉服 专卖店正品 本人" +
//                        "穿衣服很爱惜，没有任何污渍和染" +
//                        "色，而且就穿过两季，当时买的时" +
//                        "候700多吧，现在低价转，有需要" +
//                        "的联系");
//                goodsEntity.setCollectFlag(true);
//                goodsEntity.setId(1);
//                goodsEntity.setAddress("广西壮族自治区桂林市灵川县");
//                datas.add(goodsEntity);
                list.add(goodsSimpleEntity);
            }
        } else if (pageNum == 2) {
//            for (int i = 0; i < 8; i++) {
//                GoodsEntity goodsEntity = new GoodsEntity();
//                goodsEntity.setTitle("nike 纯白色棉服");
//                goodsEntity.setPrice("¥330");
//                goodsEntity.setName("布克");
//                goodsEntity.setImgurl(imgurl2);
//                goodsEntity.setAvatarurl(imgurl2);
//                goodsEntity.setDetail("nike 纯白色棉服 专卖店正品 本人\n" +
//                        "穿衣服很爱惜，没有任何污渍和染\n" +
//                        "色，而且就穿过两季，当时买的时\n" +
//                        "候700多吧，现在低价转，有需要\n" +
//                        "的联系");
//                goodsEntity.setCollectFlag(false);
//                goodsEntity.setId(1);
//                goodsEntity.setAddress("广西壮族自治区桂林市灵川县");
//                list.add(goodsEntity);
//            }
        }


        Random random = new Random();//默认构造方法
        int i = random.nextInt(2);//随机成功失败，1成功0失败
        if (true) {
            if (isRefresh) {
                refreshLayout.finishRefresh(true);
            } else {
                refreshLayout.finishLoadMore(true);
            }
            if (list != null && list.size() > 0) {
                if (isRefresh) {
                    datas = list;
//                    showToast("刷新成功！");
                } else {
                    datas.addAll(list);
//                    showToast("加载成功！");
                }
                goodsAdapter.setDatas(datas);
                goodsAdapter.notifyDataSetChanged();
            } else {
                if (isRefresh) {
                    showToast("暂时无法加载数据！");
                } else {
                    showToast("没有更多数据了！");
                }
            }
//            showToast("");
//            goodsAdapter.setDatas(datas);
//            recyclerView.setAdapter(goodsAdapter);
        } else {
            if (isRefresh) {
                refreshLayout.finishRefresh(true);
                showToast("刷新失败！");
            } else {
                refreshLayout.finishLoadMore(true);
                showToast("加载失败！");
            }
        }
    }
}